import React, { Component } from 'react';
import {
  StyleSheet, View, DeviceEventEmitter, Text, TouchableWithoutFeedback,
} from 'react-native';
import produce from 'immer';
import Timeline from 'react-native-timeline-listview';
import Theme from '../../../../native-base-theme/variables/commonColor';
import SelectPart from '../../../../components/selectIncidentpart';
import * as techDocService from '../../../../services/techDoc';
import { UtilToast } from '../../../../utils/util-method';

class ChangeHistory extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datas: [],
      showSelectIncidentPart: false,
      location: '',
      check: false,
    };
  }

  componentDidMount() {
    // this.getDatas();
  }

  getDatas = async (splitItemId) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { datas } = this.props;
      if (datas && datas.equipmentId) {
        const data = await techDocService.getChangeHistory({ equipmentId: datas.equipmentId, splitItemId });
        // const data = await techDocService.getChangeHistory({ equipmentId: '402892e467dea9fd0167e47826783426', splitItemId: '402892e467e86de70167e98c303e3b6b' });
        DeviceEventEmitter.emit('showLoading', false);
        if (data && data.length > 0) {
          this.setState(produce(draft => {
            draft.datas = data;
          }));
        } else {
          this.setState(produce(draft => {
            draft.datas = [];
          }));
          UtilToast('暂无备件更换历史信息', 'danger');
        }
        this.setState(produce(draft => { // 用来解决时间轴不刷新的问题
          draft.check = !draft.check;
        }));
      } else {
        DeviceEventEmitter.emit('showLoading', false);
        UtilToast('没有设备信息', 'danger');
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  _getDataShow = () => {
    if (!this.state.datas || !this.state.datas.length) {
      return [];
    }
    const timelineData = [];
    this.state.datas.forEach(item => {
      timelineData.push({
        failureCode: item.failureCode,
        failureId: item.failureId,
        time: item.operationTime, // 变更时间
        title: item.actionDesc,
        description: `${item.lotCode}\n${item.materialName}`,
        // icon: require('../../../../../assets/images/circle-white.png'),
      });
    });
    return timelineData;
  }

  _onItemClick = (item) => {
    const params = {
      fromNavigation: true,
      id: item.failureId,
      code: item.failureCode,
    };
    // alert(JSON.stringify(params));
    global.navigation.navigate({ routeName: 'Info', params });
  }

  renderTime = (rowData) => (
    <Text style={{
      color: '#ffffff', paddingLeft: 4, paddingRight: 4,
    }}
    >
      {rowData.time.replace(' ', '\n')}
    </Text>
  )

  renderDetail = (rowData) => {
    const title = <Text style={[styles.title]}>{rowData.title}</Text>;
    let desc = null;
    if (rowData.description) {
      desc = (
        <View style={styles.descriptionContainer}>
          <Text style={[styles.textDescription]}>{rowData.description}</Text>
        </View>
      );
    }
    return (
      <View style={{ flex: 1, marginTop: -12, marginBottom: desc ? 10 : 20 }}>
        <TouchableWithoutFeedback onPress={() => this._onItemClick(rowData)}>
          <View>
            {title}
            {desc}
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  }

  _getTimeLine = (data) => (
    <Timeline
      circleSize={16}
      circleColor="rgb(68,101,225)"
      lineColor="rgb(216,216,216)"
      timeStyle={{ color: '#ffffff' }}
      titleStyle={{ color: '#ffffff' }}
      descriptionStyle={{ color: '#ffffff' }}
      renderDetail={this.renderDetail}
      iconStyle={{ marginTop: -2 }}
      options={{
        style: { paddingTop: 8, paddingLeft: 4 },
        removeClippedSubviews: true,
      }}
      data={data}
      separator={false}
      renderTime={this.renderTime}
    />
  )

  _hideSelect = () => {
    this.setState({
      showSelectIncidentPart: false,
    });
  }

  _selectLocation = () => {
    if (this.props.datas && this.props.datas.equipmentId && this.props.datas.objType) {
      this.setState({
        showSelectIncidentPart: true,
      });
    } else {
      DeviceEventEmitter.emit('showLoading', false);
      UtilToast('没有设备信息', 'danger');
    }
  }

  _finishSelectPart = async (selectedList) => { // 故障位置选择结束
    if (selectedList && selectedList.length) {
      const material = selectedList[selectedList.length - 1];
      this.setState({ location: material.description });
      this.getDatas(material.splitItemId);
      // this.getDatas('402892e467e86de70167e98c303e3b6b');
    }
  }

  render() {
    const data = this._getDataShow();
    return (
      <View style={styles.tabContent}>
        {this.state.showSelectIncidentPart && (
          <SelectPart
            show={this.state.showSelectIncidentPart}
            hide={this._hideSelect}
            equTypeId={this.props.datas.objType}
            equipmentId={this.props.datas.equipmentId}
            finish={this._finishSelectPart}
          />
        )}
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text style={{ color: 'white', fontSize: 17 }}>位置信息</Text>
          <Text style={styles._button} onPress={() => this._selectLocation()}>选择</Text>
        </View>
        <View>
          <Text style={{ color: 'white', paddingTop: 8, paddingBottom: 8, paddingLeft: 8, fontSize: 15 }}>{this.state.location}</Text>
        </View>
        {this.state.check && (
          <View style={{ height: 1, width: '100%', backgroundColor: Theme.myPrimary }}/>
        )}
        {this.state.datas.length > 0 && (
          <View>
            <Text style={{ color: 'white', paddingTop: 8, paddingBottom: 8, fontSize: 17 }}>更换历史</Text>
          </View>
        )}
        {this.state.datas.length > 0 && this._getTimeLine(data)}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  tabContent: {
    backgroundColor: Theme.myPrimary,
    width: '100%',
    height: '100%',
    padding: 8,
  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#ffffff',
  },
  descriptionContainer: {
    flexDirection: 'row',
    paddingRight: 50,
  },
  textDescription: {
    color: '#ffffff',
  },
  _button: {
    width: 48,
    borderRadius: 2,
    textAlignVertical: 'center',
    padding: 4,
    color: 'white',
    textAlign: 'center',
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'white',
  },
});

export default ChangeHistory;
